﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using System.Xml;

namespace HlcLogViewer
{
    public class LogModel
    {
        public DateTime DateTime { get; set; }
        public LogLevel LogLevel { get; set; }
        public string Thread { get; set; }
        public string Message { get; set; }
        public string Exception { get; set; }

        public static List<LogModel> ParseLogFile(string logFilePath)
        {
            List<LogModel> logModelList = new List<LogModel>();

            var xmlDocument = new XmlDocument();
            var readAllText = File.ReadAllText(logFilePath);
            
            foreach (Match match in Regex.Matches(readAllText, "<log date=[\\W\\w]*?</log>"))
            {
                if (!match.Success)
                {
                    continue;
                }
                var logXml = match.Value;
                //logXml = logXml.Replace("&", "&amp;");
                //logXml = logXml.Replace("\\\"", "\"");
                xmlDocument.LoadXml(logXml);
                var logElement = xmlDocument.DocumentElement;

                var model = new LogModel();
                model.DateTime = DateTime.Parse(logElement.Attributes["date"].Value.Replace(",", "."));

                LogLevel level;
                if (Enum.TryParse(logElement.Attributes["level"].Value, out level))
                {
                    model.LogLevel = level;
                }

                model.Thread = logElement.Attributes["thread"].Value;
                model.Message = logElement.GetElementsByTagName("message")[0].InnerText;
                model.Exception = logElement.GetElementsByTagName("exception")[0].InnerText;
                logModelList.Add(model);
            }

            return logModelList;
        }
    }

    public enum LogLevel
    {
        FATAL = 25,
        ERROR = 20,
        WARN = 15,
        INFO = 10,
        DEBUG = 5,
    }
}